package ils.domain.catalog.model;

import ils.di.ObjectBuilder;
import ils.di.ObjectBuilderFactory;
import ils.util.HibernateSession;
import ils.util.HibernateSessionManager;
import ils.util.HibernateUtil;
import ils.util.SpringUtil;
import junit.framework.Assert;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: rejeevd
 * Date: 26/09/12
 * Time: 23:15
 * To change this template use File | Settings | File Templates.
 */
public class BookRepositoryTest
{
    private HibernateSessionManager hibernateSessionManager = new HibernateSessionManager();
    //ApplicationContext context = SpringUtil.getApplicationContext();
    ObjectBuilder objectBuilder = ObjectBuilderFactory.get();
    BookRepository bookRepository = objectBuilder.getInstance(BookRepository.class, true);

    @Test
    public void testCreateBook()
    {
        try(HibernateSession session = hibernateSessionManager.getSession())
        {
            Book book = new Book();
            book.setAuthor("Eric Evans");
            book.setTitle("Domain Driven Design");
            book.setBookType("default");
            book.setCategoryId(8);
            book = bookRepository.createBook(book);
            Assert.assertNotNull(book);
        }
    }

    @Test
    public void testTransaction(){
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        sessionFactory.getCurrentSession().beginTransaction();
        Book book = new Book();
        book.setAuthor("Eric Evans");
        book.setTitle("Domain Driven Design V2");
        book.setBookType("default");
        book.setCategoryId(8);
        book = bookRepository.createBook(book);
        Assert.assertNotNull(book);
        sessionFactory.getCurrentSession().getTransaction().commit();
    }

    @Test
    public void testGetBook()
    {
        try(HibernateSession session = hibernateSessionManager.getSession())
        {
            Book book = bookRepository.getBook(1);
            Assert.assertNotNull(book);
        }
    }

    //@Test
    public void searchBooks()
    {
        try(HibernateSession session = hibernateSessionManager.getSession())
        {
            List<Book> books = bookRepository.searchBooks("java", "title");
            Assert.assertNotSame(0, books.size());
            books = bookRepository.searchBooks("bloch", "author");
            Assert.assertNotSame(0, books.size());
            books = bookRepository.searchBooks("java", null);
            Assert.assertNotSame(0, books.size());
        }
    }
}
